/*
 * @Descripttion: 全局loading封装
 * @version:
 * @Author: lhl
 * @Date: 2024-11-17 02:08:32
 * @LastEditors: lhl
 * @LastEditTime: 2024-11-17 02:11:00
 */
import React from 'react';
import { Spin } from 'antd';
import { createRoot } from 'react-dom/client';

const GlobalLoading: React.FC = () => {
  return (
    <div
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.1)',
        zIndex: 9999,
      }}
    >
      <Spin size="large" />
    </div>
  );
};

// loading 管理类
export class LoadingService {
  // 存储 loading DOM 容器
  private static container: HTMLDivElement | null = null;
  // 存储 React root 实例
  private static root: ReturnType<typeof createRoot> | null = null;
  // loading 计数器
  private static count = 0;

  // 显示loading
  static show() {
    if (this.count === 0) {
      // 首次显示，创建容器和组件
      this.container = document.createElement('div');
      document.body.appendChild(this.container);
      this.root = createRoot(this.container);
      this.root.render(<GlobalLoading />);
    }
    this.count++;
  }

  // 隐藏loading
  static hide() {
    this.count--;
    if (this.count === 0 && this.container && this.root) {
      // 当计数为0时，移除组件和容器
      this.root.unmount();
      document.body.removeChild(this.container);
      this.container = null;
      this.root = null;
    }
  }
}

export default GlobalLoading;
